/*
 * @Author: AiLjx
 * @Date: 2022-06-29 22:54:59
 * @LastEditors: AiLjx
 * @LastEditTime: 2022-06-29 23:42:12
 */
import { useRef } from "react";
import { Mutation } from "react-apollo";
import gql from "graphql-tag";

export default function Add({ QueryListRefetch }) {
    const nameInput = useRef(null);
    const posterInput = useRef(null);
    const priceInput = useRef(null);

    const myquery = gql`
        mutation ($input: FilmInput) {
            createFilm(input: $input) {
                id
                name
                price
            }
        }
    `;

    return (
        <Mutation mutation={myquery}>
            {(createFilm, { data }) => {
                return (
                    <div>
                        名字：
                        <input type='text' ref={nameInput} />
                        封面：
                        <input type='text' ref={posterInput} />
                        价格：
                        <input type='number' ref={priceInput} />
                        <button
                            onClick={() => {
                                createFilm({
                                    variables: {
                                        input: {
                                            name: nameInput.current.value,
                                            poster: posterInput.current.value,
                                            price: Number(
                                                priceInput.current.value
                                            ),
                                        },
                                    },
                                }).then((res) => {
                                    // 调用QueryList组件的refetch，使其重新发送请求查询数据
                                    QueryListRefetch();
                                    nameInput.current.value = "";
                                    posterInput.current.value = "";
                                    priceInput.current.value = "";
                                    console.log("增加结果：", res.data);
                                    // 别忘记将请求结果return出去
                                    return res;
                                });
                            }}>
                            增加
                        </button>
                    </div>
                );
            }}
        </Mutation>
    );
}
